<template>
  <div class="outer">
    <div class="inner">
      <div class="promot">提示：按下Enter即可输出</div>
      <div class="input">
        <input type="text" v-model="array" @keyup.enter="getBalanceNum" />
        <div>请输入一个数组</div>
      </div>
      <div class="output">
        <!-- <input type="text" v-model="" /> -->
        <div>输出该数组平衡数的下标为：{{ BalanceNum }}</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Balance",
  data() {
    return {
      array: "",
      BalanceNum: -1,
    };
  },
  methods: {
    getBalanceNum() {
      // 将字符串转化为数组
      let arr = this.array.split(",");
      // 将数组中的每个元素转化为Number类型
      for (let a = 0; a < arr.length; a++) {
        arr[a] = Number(arr[a]);
      }
      let totalLeft = 0;
      let totalRight = 0;
      for (let i = 1; i < arr.length; i++) {
        if (i == 1) {
          for (let le = 0; le < i; le++) {
            totalLeft += arr[le];
          }
          for (let ri = i + 1; ri < arr.length; ri++) {
            totalRight += arr[ri];
          }
        } else {
          totalLeft += arr[i - 1];
          totalRight -= arr[i];
        }

        if (totalLeft == totalRight) {
          this.BalanceNum = i;
          return;
        }
      }
      this.BalanceNum = -1;
      return;
    },
  },
};
</script>

<style>
html {
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}

.promot {
  margin-bottom: 100px;
}

.outer {
  width: 300px;
  height: 500px;
  background-color: brown;
  border: black 2px solid;

  display: flex;
  justify-content: center;
  align-items: center;
}

.input {
  margin-bottom: 100px;
  text-align: center;
}

.output {
  text-align: center;
}
</style>